//
//  playingVC.swift
//  QQMusic
//
//  Created by xmg on 16/9/7.
//  Copyright © 2016年 wlis. All rights reserved.
//

import UIKit
import AVFoundation
import MediaPlayer
class playingVC: UIViewController {

    /** 定义属性 */
    /** 顶部的歌手 */
    @IBOutlet weak var topSinger: UILabel!
    /** 顶部的歌曲 */
    @IBOutlet weak var topSong: UILabel!
    /** 播放暂停 */
    @IBOutlet weak var bottomPlayPauseBtn: UIButton!
    /** 上一首 */
    @IBOutlet weak var bottomLastOne: UIButton!
    /** 下一首 */
    @IBOutlet weak var bottomNextHead: UIButton!
    
    /** 开始时间 */
    @IBOutlet weak var startTime: UILabel!
    /** 结束时间 */
    @IBOutlet weak var endTime: UILabel!
    /** 滚动条 */
    @IBOutlet weak var timeScrollBar: UISlider!
    /** 背景图片 */
    @IBOutlet weak var bgImage: UIImageView!
    /** 歌手图片 */
    @IBOutlet weak var singerImage: UIImageView!
    /** 歌词显示 */
    @IBOutlet weak var lyricsDisplay: lyricsLabel!
    /** 滚动的ScrollView */
    @IBOutlet weak var rollingView: lyricsSV!
    /** 定义加载数据的数组 */
    private lazy var musics : [musicItem] = [musicItem]()
    private var currentMuisc : musicItem!
    /** 创建播放对象 */
    private var player : AVAudioPlayer?
    /** 创建歌词定时器 */
    private var progressTimer : NSTimer?
    /** 创建图片歌词定时器 */
    private var lrcTimer : CADisplayLink?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    
    }
    
}

// MARK: -  设置
extension playingVC{

    private func setUpUI(){
       
        setHairGlass()
        setSingerImage()
        setPlayData()
        currentMuisc = musics[2]
        setPlaySong()
        
    }
    
    /** 设置毛玻璃 */
    private func setHairGlass(){
        if #available(iOS 8.0, *) {
            let effect = UIBlurEffect(style: .Dark)
            let blurView = UIVisualEffectView(effect: effect)
            blurView.frame = view.bounds
            bgImage.addSubview(blurView)
        } else {
            UIScreen.mainScreen().bounds
            let toolB = UIToolbar(frame: UIScreen.mainScreen().bounds)
            toolB.barTintColor = UIColor.clearColor()
            bgImage.addSubview(toolB)
            
        
        }
        
    }
    /** 设置歌手图片样式 */
    private func setSingerImage(){
        /** 添加一个滑块的的图片样式 */
       timeScrollBar.setThumbImage(UIImage(named: "player_slider_playback_thumb"), forState: .Normal)
        singerImage.layer.cornerRadius = singerImage.bounds.width * 0.5
        singerImage.layer.borderWidth = 8
        singerImage.layer.borderColor = UIColor.purpleColor().CGColor
        singerImage.layer.masksToBounds = true
        /** 设置歌词的View  */
        rollingView.contentSize = CGSize(width: view.frame.width * 2, height: 0)
        /** 设置代理 */
        rollingView.delegate = self
        rollingView.lyricsDelegate = self
        /** 水平滚动条隐藏 */
        rollingView.showsHorizontalScrollIndicator = false
        /** 垂直滚动条隐藏 */
        rollingView.showsVerticalScrollIndicator = false
    }
    /** 加载数据 */
    private func  setPlayData(){
    let filePath = NSBundle.mainBundle().pathForResource("Musics.plist", ofType: nil)
        let musicsArray = NSArray(contentsOfFile: filePath!)
        for dict in musicsArray!{
            musics.append(musicItem(dict: dict as! [String : NSObject]));
        }
    }
    
    /** 设置播放歌曲 */
    private func setPlaySong(){
      bgImage.image = UIImage(named: currentMuisc.icon)
        singerImage.image = UIImage(named: currentMuisc.icon)
        topSong.text = currentMuisc.name
        topSinger.text = currentMuisc.singer
//        bottomPlayPauseBtn.selected = true
        timeScrollBar.value = 0
        
        player = musicTools.playMusicWithFileName(currentMuisc.filename)
        player!.delegate = self
        startTime.text = "00:00"
        endTime.text = stringWithTime(player?.duration ?? 0)
        /** 开启定时器 */
        removeProgressTimer()
        setUpProgressTimer()
        removeLrcTimer()
        setUpLrcTimer()
        rollingView.lrcName = currentMuisc.lrcname
        rollingView.iconName = currentMuisc.icon
        setUpLockScreen(UIImage(named: currentMuisc.icon)!)
    }
    /** 转换时间为字符串 */
    private func stringWithTime(time : NSTimeInterval) -> String {
        let min = Int(time + 0.1) / 60
        let second = Int(time + 0.1) % 60
        
        return String(format: "%02d:%02d", arguments: [min, second])
    }
    
    /** 设置旋转歌手头像 */
    private func setRotatingHead(){
        // 1.创建动画(CABasic/CAKeyFrame)
        let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
        
        // 2.给动画设置属性
        rotationAnim.fromValue = 0
        rotationAnim.toValue = M_PI * 2
        rotationAnim.repeatCount = MAXFLOAT
        rotationAnim.duration = 30
        
        // 让View在覆盖或者消失后, 重新出现, 动画依然执行
        rotationAnim.removedOnCompletion = false
        /** 设置转动 */
        singerImage.layer.addAnimation(rotationAnim, forKey: nil);
    }
    
}

extension playingVC: AVAudioPlayerDelegate{
    /** 播放下一首歌曲 */
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
        NextHeadClick(bottomPlayPauseBtn)
        }
    }
}

// MARK: - 底部条点击事件
extension playingVC{

    /** 开始和暂停播放 */
    @IBAction func PlayPause(sender: UIButton) {
        sender.selected = !sender.selected
        if sender.selected{
            /** 添加定时器 */
//            setUpProgressTimer()
            /** 开始播放 */
             player?.play()
            setRotatingHead()
            /** 开始动画 */
            singerImage.layer.resumeAnimation()
           
        }else{
            player?.pause();
            /** 暂停动画 */
            singerImage.layer.pauseAnimation()
        }
        
        
        
    }
    /** 播放上一曲 */
    @IBAction func LastOneClick(sender: AnyObject) {
        bottomPlayPauseBtn.selected = false
      var index = musics.indexOf(currentMuisc)
      index  = index! + 1 > musics.count - 1 ? 0 : index! + 1
      
      self.currentMuisc = musics[index!]
      setPlaySong()
//      player?.play()
    }
    /** 播放下一曲 */
    @IBAction func NextHeadClick(sender: UIButton) {
        bottomPlayPauseBtn.selected = false
    var index = musics.indexOf(currentMuisc)!
        index = index - 1 < 0 ? musics.count - 1 : 0
        self.currentMuisc = musics[index]
        setPlaySong()
    
    }
    
    
    @IBAction func sliderValueChanged(sender: UISlider) {
        let ratio = timeScrollBar.value
        let duration = player?.duration ?? 0
        let currentTime = duration *  NSTimeInterval(ratio)
        startTime.text = stringWithTime(currentTime)
        
    }
    
    @IBAction func sliderUpOutside(sender: UISlider) {
        /** 开启定时器 */
        setUpProgressTimer();
        let currentTime = (player?.duration ?? 0) * NSTimeInterval(timeScrollBar.value)
        player?.currentTime = currentTime
    }
    @IBAction func sliderUpInside(sender: UISlider) {
        /** 开启定时器 */
        setUpProgressTimer();
        let currentTime = (player?.duration ?? 0) * NSTimeInterval(timeScrollBar.value)
        player?.currentTime = currentTime
    }
    @IBAction func sliderDown(sender: UISlider) {
        removeProgressTimer()
    }
    /** 加入手势点击按钮 */
    @IBAction func sliderTapGesture(sender: UITapGestureRecognizer) {
        let point = sender.locationInView(timeScrollBar)
        let ratio = point.x / timeScrollBar.bounds.width
        
        let cuttentTime = (player?.duration ?? 0) * NSTimeInterval(ratio)
        
        startTime.text = stringWithTime(cuttentTime)
        
        player?.currentTime = cuttentTime
        timeScrollBar.value = Float(ratio)
    }
}
// MARK: - 遵守协议
extension playingVC :UIScrollViewDelegate,lyricsSVDelegate{
    /** 设置滚动区域 */
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let offset = scrollView.contentOffset
        /** 计算比例 */
        let ration = offset.x / scrollView.bounds.width
        /** 设置空间的透明度 */
        UIView.animateWithDuration(0.15) { () -> Void in
            self.singerImage.alpha = 1 - ration
            self.lyricsDisplay.alpha = 1 - ration
        }
        
    }
    func lyricsSVImage(lrcView: lyricsSV, drawImage: UIImage) {
        setUpLockScreen(drawImage)
    }
    func lyricsSVText(lrcView: lyricsSV, lrcText: String, progress: CGFloat) {
        lyricsDisplay.text = lrcText
        lyricsDisplay.progress = progress
    }

    
}
// MARK: - 添加定时器
extension playingVC{
    /** 设置定时器 */
    private func setUpProgressTimer(){
    progressTimer = NSTimer(fireDate: NSDate(), interval: 1.0, target: self, selector: "updateProgressInfo", userInfo: nil, repeats: true)
    NSRunLoop.mainRunLoop().addTimer(progressTimer!, forMode: NSRunLoopCommonModes)
    }
    /** 移除定时器 */
    private func removeProgressTimer() {
        progressTimer?.invalidate()
        progressTimer = nil
    }
    @objc private func updateProgressInfo(){
        // 1.获取当前时间
        let currentTime = player?.currentTime ?? 0
        let duration = player?.duration ?? 0
        startTime.text = stringWithTime(currentTime)
        
        // 2.改变slider的进度
        timeScrollBar.value = Float(currentTime / duration)

    }
    
    private func setUpLrcTimer(){
    lrcTimer = CADisplayLink(target: self, selector: "updateLrcTime")
        lrcTimer?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
    }
    /** 删除 */
    private func removeLrcTimer() {
        lrcTimer?.invalidate()
        lrcTimer = nil
    }
    
    @objc private func updateLrcTime() {
        rollingView.currentTime = player?.currentTime ?? 0
    }
}

extension playingVC    {
    private func setUpLockScreen(image : UIImage){
    
        let centerinfo = MPNowPlayingInfoCenter.defaultCenter()
        /** 设置界面 */
        var newDict = [String :NSObject]()
        newDict[MPMediaItemPropertyArtist] = currentMuisc.singer
        newDict[MPMediaItemPropertyAlbumTitle] = currentMuisc.name
        newDict[MPMediaItemPropertyPlaybackDuration] = player?.duration ?? 0
        let art = MPMediaItemArtwork(image: image)
        newDict[MPMediaItemPropertyArtwork] = art
        centerinfo.nowPlayingInfo = newDict
        
        /** 让应用程序成为第一响应者 */
        UIApplication.sharedApplication().becomeFirstResponder()
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
        
    }
    override func remoteControlReceivedWithEvent(event: UIEvent?) {
        switch event!.subtype{
        case .RemoteControlPreviousTrack:
             LastOneClick(bottomPlayPauseBtn)
        case .RemoteControlNextTrack:
            NextHeadClick(bottomPlayPauseBtn)
        case .RemoteControlPause, .RemoteControlPlay:
           PlayPause(bottomPlayPauseBtn)
        default:
            print("不接受的事件")
        }
    }

}

